<script setup>
import { Plus } from '@element-plus/icons-vue';
import { ref } from 'vue'
import { useFileToBase64 } from '@/components/flieToBase64'
import { updateMyImg } from '@/api/MyselfApi'

// 用来显示图片的盒子
const imgUrl = ref(null)
// 用来准备提交的盒子
const postUrl = ref(null)
// 用来装插件框的
const elImg = ref()
const loading = ref(false)

// 上传照片逻辑
  const getImgUrl = async (uploadFile) => {
    imgUrl.value = URL.createObjectURL(uploadFile.raw)
    const file = uploadFile.raw
    // postUrl.value = uploadFile.raw
    try {
      const base64 = await useFileToBase64(file);
      postUrl.value = base64;
      console.log('转换成功:', base64.substring(0, 50) + '...');
    } catch (error) {
      console.error('转换失败:', error.message);
    }
    // console.log('执行到这里代表准备提交图片格式已经正确',postUrl.value)
  }
  // 点击上传
  const updateImg = async () => {
    loading.value = true
    await updateMyImg(postUrl.value)
    loading.value = false
    history.go(0)
    // console.log('修改照片后个人数据',res)
  }

</script>

<template>
  <div class="maxBox"
    v-loading="loading"
    element-loading-text="拼命加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.7)"
  >
    <div class="top">
      <div class="title">更换头像</div>
    </div>
    <div class="foot">
      <div class="img">
        <!-- <img src="../../../public/ren.png" alt=""> -->
          <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" :on-change="getImgUrl" ref="elImg">
            <img v-if="imgUrl" :src="imgUrl" class="imgUrl" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
      </div>
      <div>
        <button class="btn btn1" @click="elImg.$el.querySelector('input').click()">选择图片</button>
        <button class="btn btn2" @click="updateImg">上传头像</button>
      </div>
    </div>
  </div>

</template>

<style scoped>
  * {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    /* border: 1px solid red; */
  }
  .maxBox {
    width: 980px;
    min-height: 1000px;
  }
  /* top样式开始 */
  .top {
    width: 100%;
    height: 80px;
    /* position: relative; */
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .title {
    width: 200px;
    height: 100%;
    text-align: center;
    line-height: 80px;
    font-weight: 700;
    color: black;
    font-size: 40px;
  }
  /* top样式结束 */
  .foot {
    width: 100%;
  }
  .img {
    width: 300px;
    height: 300px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    cursor: pointer;
    /* border: 1px solid black; */
    font-size: 100px;
  }
  .img img {
    width: 100%;
    height: 100%;
    object-fit: cover
  }
  .btn1 {
    margin-left: 45px;
  }
  .btn2 {
    margin-left: 10px;
  }
</style>